<?php
/**
 * Created by PhpStorm.
 * User: joe
 * Date: 17-10-31
 * Time: 下午2:27
 */

if (!function_exists('site_url')) {
    function site_url($url) {
        $config = new \System\Config();
        return $config->baseUrl . $url;
    }
}
//------------------------------------------------------------------------
//创建多级目录
if (!function_exists('mkdirs')) {
    /**
     * @param string $dir
     * @param int $mode
     *
     * @return bool
     */
    function mkdirs($dir, $mode = 0777) {
        if (is_dir($dir) || @mkdir($dir, $mode))
            return TRUE;
        if (!mkdirs(dirname($dir), $mode))
            return FALSE;
        return @mkdir($dir, $mode);
    }
}
if (!function_exists('logs')) {

    function logs($message, $type = 'Error') {
        $log_file=fopen(BASE_PATH . '/Logs/' . date('Y-m-d') . '.php','a+');
        fputs($log_file, sprintf(date('H:i:s ') . " - %s: %s \n", $type, $message));
        fclose($log_file);
    }
}

if (!function_exists('showError')) {
    function showError($message,$header="HTTP/1.0 500 Has An Error",$title='') {
        $config = new \System\Config();
        header($header);
        $title=$title?:'500 Has An Error';
        $messages=new \System\Exception($message);
        logs($messages);
        $messages=str_replace(array("\r\n", "\r", "\n"),'<br/>',$messages);
        $viewPath='App/Views/error/';
        include $config->view['path'].'/error/Error.html';
    }
}

if (!function_exists('redirect')) {
    function redirect($url) {
        $regex = '@(?i)\b((?:[a-z][\w-]+:(?:/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:\'".,<>?«»“”‘’]))@';
        $url=(preg_match($regex, $url))?$url:site_url($url);
        header("Location: ".$url);
        exit;
    }
}


if (!function_exists('charEncode')) {
    /**
     * @param string $data
     * @param string $to 输出字符串编码,默认'utf-8'
     *
     * @return string
     */
    function charEncode($data, $to = 'UTF-8') {
        $encode_arr = [
            'UTF-8',
            'ASCII',
            'GBK',
            'GB2312',
            'BIG5',
            'JIS',
            'eucjp-win',
            'sjis-win',
            'EUC-JP',
        ];
        $encoded = mb_detect_encoding($data, $encode_arr);
        $data = mb_convert_encoding($data, $to, $encoded);

        return $data;
    }
}


if (!function_exists('grab_image')) {
    /**
     * 远程下载图片到服务器函数
     * @param string $url
     * @param string $filename
     * @param string $directory
     *
     * @return bool|string
     */
    function grab_image($url, $filename = "", $directory = '') {

        if ($url == "") {
            return false;
        }

        $ext = strtolower(strrchr($url, "."));
        $ext_arr = [
            ".gif",
            ".png",
            ".jpg",
            ".bmp",
            ".jpeg"
        ];
        //判断扩展名是否为图片
        if (!in_array($ext, $ext_arr)) {
            return false;
        }

        $filename .= $ext;

        if (!is_dir($directory)) {
            mkdirs($directory);
            $filename = $directory . $filename;
        }
        ob_start();
        readfile($url);
        $img = ob_get_contents();
        ob_end_clean();
        if (!$img) {
            return false;
        }
        $fp = fopen($filename, "a");
        fwrite($fp, $img);
        fclose($fp);
        return $filename;
    }
}

if (!function_exists('html_escape')) {
    /**
     * Returns HTML escaped variable.
     *
     * @param    mixed $var The input string or array of strings to be escaped.
     * @param    bool $double_encode $double_encode set to FALSE prevents escaping twice.
     *
     * @return    mixed            The escaped string or array of strings as a result.
     */
    function html_escape($var, $double_encode = TRUE) {
        if (empty($var)) {
            return $var;
        }

        if (is_array($var)) {
            foreach (array_keys($var) as $key) {
                $var[$key] = html_escape($var[$key], $double_encode);
            }

            return $var;
        }

        return htmlspecialchars($var, ENT_QUOTES, config_item('charset'), $double_encode);
    }
}

